<?php
declare (strict_types=1);

namespace app\common\model;

class OrderProduct extends Base
{
    public static function add($products, $order_id)
    {
        try {
            $orders = [];
            foreach ($products as $k => $v) {
                $product = Product::where('id', $v['id'])->find();
                if ($product['stock'] < $v['num']) {
                    return ['code' => -1, 'msg' => "《" . $v['title'] . "》库存不足！"];
                }
                $orders[$k] = [
                    'order_id' => $order_id,
                    'pid' => $product->id,
                    'product_title' => $product->title,
                    'num' => $v['num'],
                    'product_image' => $product->icon,
                    'price' => $product->price
                ];
            }
            if (!empty($orders)) {
                parent::insertAll($orders);
            }

        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }
}